﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections;
using System.Data;
using CMSModel;
using DAL;
using System.Text.RegularExpressions;
using BLL;

/// <summary>
///  导入BBS的数据
/// </summary>
public class BBSDataCatch
{
    private readonly string BBSID_PRE = "BBSID:";

    public void Import()
    {
        DAL.BBSDAL bbsdal = new DAL.BBSDAL();
        string[][] tids = new string[][] { 
            new string[] { "13688", "胡俍观点" }, 
            new string []{"13687","方达点睛"},
            new string []{"13686","布衣解盘"},
            new string [] {"13798","天涯看盘"},
            new string []{"13908","顾勇菁"},
            new string []{"13909","曹茂桂"},
            new string []{"13910","刘哲"},
            new string [] {"13911","顾亚斌"},
            new string [] {"13912","顾旭明"}
        };
        AddNewsList(tids, "0704", 1);
        tids = new string[][] { new string[] { "5", "乾坤版战法" } };
        AddNewsList(tids, "1201", 2);
        tids = new string[][] { new string[] { "8", "主力版战法" } };
        AddNewsList(tids, "1202", 2);
        tids = new string[][] { new string[] { "56", "决策版战法" } };
        AddNewsList(tids, "1203", 2);
        tids = new string[][] { new string[] { "44", "盯盘先锋战法" } };
        AddNewsList(tids, "1204", 2);
    }

    public void AddNewsList(string[][] tids, string NewsTypeId, int type)
    {
        DAL.BBSDAL bbsdal = new DAL.BBSDAL();
        for (int i = 0; i < tids.Length; i++)
        {
            DataTable tb = null;
            switch (type) 
            {
                case 1:
                    tb = bbsdal.GeteData(tids[i][0], 50);
                    break;
                case 2:
                    tb = bbsdal.GeteDataByTypeid(int.Parse(tids[i][0]), 50);
                    break;
                default:
                    tb = bbsdal.GeteData(tids[i][0], 50);
                    break;
            }
            foreach (DataRow row in tb.Rows)
            {
                CMSModel.News news = new CMSModel.News();
                news.author = row["author"].ToString();
                news.ctime = DateTime.Parse("1970-1-1").AddSeconds(double.Parse(row["dateline"].ToString()));
                news.title = row["subject"].ToString();
                news.content = Tools.GetString(row["message"]);
                string tags = Tools.GetString(row["tags"]);
                news.keyword = string.IsNullOrEmpty(tags) ? news.title : tags;
                news.OutsideUrl = "http://bbs.emoney.cn/thread-" + row["tid"].ToString() + "-1-1.html";
                news.step = 0;
                string bbsid = Tools.GetLong(row["tid"]).ToString();

                BBS_Post post = new BBS_Post();
                post.Allowhtml = Tools.GetInt(row["htmlon"]).Value;
                post.Bbcodeoff = Tools.GetInt(row["Bbcodeoff"]).Value;
                post.Sdetail = Tools.GetString(row["message"]);
                news.Source = "益盟操盘手";
                news.content = UBBTools.UBBToHTML(post);
                news.content = Regex.Replace(news.content, @"<i[^>]*>((?!</i>).)*</i>", "");
                news.content = Regex.Replace(news.content, "</tr>((?!<tr>).)*<tr>", "</tr><tr>");
                news.content = Regex.Replace(news.content, "\\[attach\\]((?!\\[/attach\\]).)*\\[/attach\\]", RmAttachment);
                news.content = Regex.Replace(news.content, "\\[p=[^\\]]*\\]", "");
                news.content = news.content.Replace("[/p]", "");
                news.content = Regex.Replace(news.content, "\\[backcolor=[^\\]]*\\]", "");
                news.content = news.content.Replace("[/backcolor]", "");

                string summary = news.content;
                summary = Regex.Replace(summary, @"<[^>]*>", "");
                summary = Regex.Replace(summary, "</[^>]*>", "");
                summary=Regex.Replace(summary,"\\[[^(\\])]*\\]","");
                if (summary.Length > 301)
                {
                    news.Summary = summary.Substring(0, 300);
                }
                else
                {
                    news.Summary = summary;
                }
                AddNews(bbsid, news, NewsTypeId);
            }
        }
    }

    public void AddNews(string bbsId, CMSModel.News news, string NewsTypeid)
    {
        //判断这个股票是不是已经添加过了
        if (IsCheck(bbsId))
        {
            return;
        }
        CMSEntities cms = new CMSEntities();
        News_Type newsType = new News_Type();
        newsType.NewsTypeId = NewsTypeid;
        newsType.ctime = DateTime.Now;
        news.News_Type.Add(newsType);
        news.IsEnable = true;
        news.ptime = DateTime.Now;
     
        cms.News.AddObject(news);
        cms.SaveChanges();
        NewsCatch nCatch = new NewsCatch();
        nCatch.url = BBSID_PRE + bbsId;
        nCatch.NewsID = news.id;
        nCatch.CTime = DateTime.Now;
        cms.NewsCatch.AddObject(nCatch);
        cms.SaveChanges();
    }

    bool IsCheck(string bbsId)
    {
        string str = BBSID_PRE + bbsId;
        CMSEntities cms = new CMSEntities();
       
        return cms.NewsCatch.Any(x => x.url == str);
    }


    static string RmAttachment(Match m)
    {
        try
        {
            string aa = m.Value;
            aa = aa.Replace("[attach]", "").Replace("[/attach]", "");
            long aid = long.Parse(aa);
            aa = Convert.ToBase64String(System.Text.Encoding.GetEncoding("GB2312").GetBytes(aa));
            System.Data.DataRow row =new BBSDataCatch().GetAttachment(aid);
            int isimage = DAL.Tools.GetInt(row["isimage"]).Value;
            if (isimage == 1)
            {
                int width = DAL.Tools.GetInt(row["width"]).Value;
                if (width > 600)
                {
                    width = 600;
                }
                string strWidth = width == 0 ? "" : "width=\"" + width + "\"";
                string url = "http://bbs.emoney.cn/forum.php?mod=attachment&aid=" + aa + "&noupdate=yes";
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                sb.Append("<p align=\"center\">");
                sb.Append("<img src=\"http://bbs.emoney.cn/forum.php?mod=attachment&aid=" + aa + "\" alt=\"\"" + strWidth + " />");
                sb.Append("</p>");
                return sb.ToString(); ;
            }
            else
            {
                return "";
            }
        }
        catch
        {
            return "";
        }
    }

    public DataRow GetAttachment(long aid)
    {
        BBSDAL bbsdal = new BBSDAL();
        DataTable tb = bbsdal.GetAttachment(aid);
        if (tb.Rows.Count > 0)
        {
            return tb.Rows[0];
        }
        else
        {
            return null;
        }
    }
}